<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_User extends Controller_Admin {

    private $a_Act = array("List Active Resident", "List Active Employees", "List In-Active Resident", 'List In-Active Employees');

    public function before() {
        parent::before();
        $this->setActive_menu_left('user');
    }

    private function hander_user_list($filter, $sort) {

        $a_pagination = Kohana::$config->load("pagination");
        $page = Arr::get($_GET, 'page') == "" ? 1 : Arr::get($_GET, 'page');
        $items_per_page = Arr::get($_GET, 'size') != "" ? Arr::get($_GET, 'size') : Arr::path($a_pagination, 'admin.items_per_page');
        $to = $page * $items_per_page;
        $offset = $to - $items_per_page;
        $a_pagination->admin["items_per_page"] = $items_per_page;

        $s_user = new Model_Service_User();

        $a_user = $s_user->get_all_user(false, $filter, $sort, $items_per_page, $offset);

        $n_count_all = $s_user->get_all_user(true, $filter, $sort);

        Arr::set_path($a_pagination, 'admin.total_items', $n_count_all);
        $pagination = new Pagination(Arr::get($a_pagination, 'admin'));

        return array('pagination' => $pagination->render(), 'a_user' => $a_user);
    }

    public function action_get_data() {
        header('Content-type: application/json');



        $filter = array(
            'active' => $_REQUEST['active']
        );



        if (!empty($_REQUEST['textsearch'])) {
            $textsearch = trim($_REQUEST['textsearch']);
            $filter['where open'] = null;
            $filter['fname'] = array('or like' => $textsearch);
            $filter['lname'] = array('or like' => $textsearch);

            $filter['email'] = array('or like' => $textsearch);

            $filter['house_number'] = array('or like' => $textsearch);
            $filter['username'] = array('or like' => $textsearch);
            $filter['phone'] = array('or like' => $textsearch);
            $filter['where close'] = null;
        }

        $sort = array(
            $_REQUEST['sortname'] => $_REQUEST['sortdir']
        );

        $a_result = $this->hander_user_list($filter, $sort);
        $a_data = array();
        $a_data['data'] = array();
        $a_data['pagination'] = $a_result['pagination'];




        if (!empty($a_result['a_user'])) {
            foreach ($a_result['a_user'] as $obj) {
                $en_user = $obj->get_data();
                $a_item = array();
                $a_item['id'] = $en_user->getId();
                $a_item['name'] = $en_user->getlname() . " " . $en_user->getfname();

                $a_item['phone'] = $en_user->getphone();
                $a_item['address'] = $en_user->gethouse_number();
                $a_item['imagename'] = $en_user->getImagename();
                $a_item['email'] = $en_user->getEmail();
                if (!empty($a_item['imagename'])) {
                    $a_item['imagename'] = $this->_url_base_media . "/" . Controller_Helper_Constant::FOLDER_AVATAR . "/" . $a_item['imagename'];
                } else {
                    $a_item['imagename'] = $this->_url_base_media . "/assets/img/avatars/profile-pic.jpg";
                }
                $a_data['data'][] = $a_item;
            }
        }

        echo json_encode($a_data);
        die;
    }

    public function action_list() {
        $this->setActive_menu_left('userlist');

        $filter = array(
            'active' => Arr::get($_REQUEST, 'active', 1)
        );

        $sort = array(
            'fname' => 'asc'
        );
        $searchtext = Arr::get($_REQUEST, 'textsearch');
        if (!empty($searchtext)) {
            $textsearch = trim($_REQUEST['textsearch']);
            $filter['where open'] = null;
            $filter['fname'] = array('or like' => $textsearch);
            $filter['lname'] = array('or like' => $textsearch);

            $filter['email'] = array('or like' => $textsearch);

            $filter['house_number'] = array('or like' => $textsearch);
            $filter['username'] = array('or like' => $textsearch);
            $filter['phone'] = array('or like' => $textsearch);
            $filter['where close'] = null;
        }

        $a_result = $this->hander_user_list($filter, $sort);

        $breadcrumbs = array(
            "People" => "",
            "List" => "",
        );


        $this->add_css(array('select2', 'upload', 'datepicker', 'group', 'multi-select'));

        $this->add_js(array(
            'fuelux/fuelux.wizard.min',
            'jquery.validate.min',
            'additional-methods.min',
            'bootbox.min',
            'jquery.maskedinput.min',
            'select2.min',
            'ace-elements.min',
            'ace.min',
            'ajaxupload',
            'date-time/bootstrap-datepicker.min',
            'include/user/edit',
            'jquery.dataTables.min',
            'jquery.dataTables.bootstrap',
            'ace-elements.min',
            'knockout',
            'include/user/user_objects',
            'include/user/list',
            'jquery.multi-select'
        ));


        $this->template->content = View::factory("admin/user/list")
                ->set('breadcrumbs', $breadcrumbs)
                ->set('a_user', $a_result['a_user'])
                ->set('pagination', $a_result['pagination'])
                ->set('title', $this->a_Act[0])
        ;
    }

    public function action_deleted() {
        header('Content-type: application/json');
        $id = Arr::get($_REQUEST, 'id');
        $s_user = new Model_Service_User();
        $en_user = $s_user->load($id)->get_data();
        $a_data = array();
        $a_data['error'] = 0;

        

        if ((int) $en_user->getId() <= 0) {
            $a_data['error'] = 1;
            $a_data['msg'] = "User is not exsting.";
            echo json_encode($a_data);
            die;
        }
        $s_user->delete($id);
        $url_delete = $this->getUrl_base_media() . "/delete_file.php";
        if (trim($en_user->getimagename()) != "") {
            $request = Request::factory($url_delete)
                    ->method('POST')
                    ->post('fromfolder', Controller_Helper_Constant::FOLDER_AVATAR)
                    ->post('filename', $en_user->getimagename());
            $response = $request->execute();
        }
        $a_data['msg'] = Kohana::message('en/admin/user/success', 'delete');

        echo json_encode($a_data);
        die;
    }

    public function action_add() {
        $this->setActive_menu_left('useradd');

        $this->add_js(array(
            'fuelux/fuelux.wizard.min',
            'jquery.validate.min',
            'additional-methods.min',
            'bootbox.min',
            'jquery.maskedinput.min',
            'select2.min',
            'ace-elements.min',
            'ace.min',
            'ajaxupload',
            'date-time/bootstrap-datepicker.min',
            'include/user/add',
            'jquery.multi-select'
        ));

        $this->add_css(array('select2', 'upload', 'datepicker', 'group', 'multi-select'));

        $en_user = new Domain_Entities_User();


        $s_user = new Model_Service_User();

        // get all permission
        $s_p_controller = new Model_Service_Permission_Controller;
        $a_p_controller = $s_p_controller->load_all();
        // get all group
        $s_group = new Model_Service_Group();
        $a_group = $s_group->load_all();
        // vail group , permission
        $a_group_id = array();
        $a_permission_id = array();
        if (!$_POST) {
            
        } else {
            header('Content-type: application/json');
            $a_post = $_POST;
            $a_permission_id = empty($a_post['permission_id']) ? null : $a_post['permission_id'];
            $a_group_id = empty($a_post['group_id']) ? null : $a_post['group_id'];
            $en_user->set_array_to_object($a_post);
            $en_user->setDob(Controller_Helper_Format::format_date($en_user->getDob(), 'm/d/Y', "Y-m-d"));
            $en_user->setadmin_userid($this->_user->getId());
            $result = array();
            $result['error'] = 0;

            $en_user_check = $s_user->get_by_username($en_user->getUserName())->get_data();
            if ($en_user_check->getId() > 0) {
                $result['error'] = 1;
                $result['id'] = 'username';
                $result['msg'] = "User is exsting.";
                echo json_encode($result);
                die;
            }

            if (empty($result['msg'])) {
                $o_user = $s_user->insert($en_user);
                if (trim($en_user->getimagename()) != "") {
                    $url_move = $this->getUrl_base_media() . "/move_file.php";
                    $request = Request::factory($url_move)
                            ->method('POST')
                            ->post('fromfolder', Controller_Helper_Constant::FOLDER_TEMP)
                            ->post('tofolder', Controller_Helper_Constant::FOLDER_AVATAR)
                            ->post('filename', $en_user->getimagename());
                    $response = $request->execute();
                }
                if (!empty($o_user)) {
                    $o_entity_user = $o_user->get_data();
                    $n_user_id = $o_entity_user->getId();
                    //add User Permission
                    if (!empty($a_permission_id) && is_array($a_permission_id)) {
                        $s_up = new Model_Service_User_Permission();
                        foreach ($a_permission_id as $n_permission_id) {
                            $o_entity_up = new Domain_Entities_User_Permission;
                            $o_entity_up->setPermission_Id($n_permission_id);
                            $o_entity_up->setUser_Id($n_user_id);
                            $s_up->insert($o_entity_up);
                        }
                    }
                    //add User Group
                    if (!empty($a_group_id) && is_array($a_group_id)) {
                        $s_ug = new Model_Service_User_Group();
                        foreach ($a_group_id as $n_group_id) {
                            $o_entity_ug = new Domain_Entities_User_Group();
                            $o_entity_ug->setGroup_Id($n_group_id);
                            $o_entity_ug->setUser_Id($n_user_id);
                            $s_ug->insert($o_entity_ug);
                        }
                    }
                }
                $o_message = Controller_Helper_Message::get_instance();
                $o_message->set_success('add', $this->getLanguage() . '/admin/user/success');
            }
            echo json_encode($result);
            die;
        }
        $breadcrumbs = array(
            "People" => "",
            "Add" => "",
        );
        $this->template->content = View::factory("admin/user/new")
                ->set('breadcrumbs', $breadcrumbs)
                ->set('en_user', $en_user)
                ->set('a_p_controller', $a_p_controller)
                ->set('a_group', $a_group);
    }

    public function action_profile() {
        $this->add_css(array('select2', 'upload', 'datepicker', 'group', 'multi-select'));

        $this->add_js(array(
            'fuelux/fuelux.wizard.min',
            'jquery.validate.min',
            'additional-methods.min',
            'bootbox.min',
            'jquery.maskedinput.min',
            'select2.min',
            'ace-elements.min',
            'ace.min',
            'ajaxupload',
            'date-time/bootstrap-datepicker.min',
            'include/user/profile',
            'jquery.dataTables.min',
            'jquery.dataTables.bootstrap',
            'ace-elements.min',
            'knockout',
            'jquery.multi-select'
        ));

        $result = array();
        $id = $this->_user->getId();
        $result['error'] = 0;
        $a_group_id = array();
        $a_permission_id = array();
        $s_up = new Model_Service_User_Permission();
        $s_ug = new Model_Service_User_Group();
        $s_user = new Model_Service_User();
        $en_user = $s_user->load($id)->get_data();
        $image_old = $en_user->getimagename();



        if ((int) $en_user->getId() <= 0) {
            $result['error'] = 1;
            $result['msg'] = "User is not exsting.";
            echo json_encode($result);
            die;
        }


       
        if (!$_POST) {

        } else {
            header('Content-type: application/json');
            $a_post = $_POST;

            $en_user->set_array_to_object($a_post);
            $en_user->setedituserid($this->_user->getId());
            $en_user->setDob(Controller_Helper_Format::format_date($en_user->getDob(), 'm/d/Y', "Y-m-d"));
            $result = array();
            $result['error'] = 0;
            
            $result = $s_user->valid_edit($en_user, 'en/admin/user/error');


            if (empty($result['msg'])) {
                $o_user = $s_user->update($en_user);
                if (!empty($o_user)) {
                    $o_entity_user = $o_user->get_data();
                    $n_user_id = $id;
                }
                if (trim($en_user->getimagename()) != "" && $image_old != trim($en_user->getimagename())) {
                    $url_move = $this->getUrl_base_media() . "/move_file.php";
                    $request = Request::factory($url_move)
                            ->method('POST')
                            ->post('fromfolder', Controller_Helper_Constant::FOLDER_TEMP)
                            ->post('tofolder', Controller_Helper_Constant::FOLDER_AVATAR)
                            ->post('filename', $en_user->getimagename());
                    $response = $request->execute();

                    //delete file
                    $url_delete = $this->getUrl_base_media() . "/delete_file.php";

                    $request = Request::factory($url_delete)
                            ->method('POST')
                            ->post('fromfolder', Controller_Helper_Constant::FOLDER_AVATAR)
                            ->post('filename', $image_old);
                    $response = $request->execute();
                }
                $result['msg'] = Kohana::message('en/admin/user/success', 'edit');
            }
            echo json_encode($result);
            die;
        }
        //get permission controller
        $s_p_controller = new Model_Service_Permission_Controller;
        $a_p_controller = $s_p_controller->load_all();

        //get all group
        $s_group = new Model_Service_Group;
        $a_group = $s_group->load_all();
        $breadcrumbs = array(
            "My Profile" => "",
        );

        $this->template->content = View::factory("admin/user/myprofile")
                        ->set('breadcrumbs', $breadcrumbs)
                        ->set('en_user', $en_user)
                      
                        ->set('a_p_controller', $a_p_controller)
                        ->set('a_group', $a_group)
                        ->set('a_permission_id', $a_permission_id)
                        ->set('a_group_id', $a_group_id)->render();
    }

    public function action_edit() {
        $this->setActive_menu_left('useredit');
        header('Content-type: application/json');
        $result = array();
        $id = Arr::get($_REQUEST, 'id');
        $result['error'] = 0;
        $a_group_id = array();
        $a_permission_id = array();
        $s_up = new Model_Service_User_Permission();
        $s_ug = new Model_Service_User_Group();
        $s_user = new Model_Service_User();
        $en_user = $s_user->load($id)->get_data();
        $image_old = $en_user->getimagename();

        

        if ($en_user->getId() <= 0) {
            $result['error'] = 1;
            $result['msg'] = "User is not exsting.";
            echo json_encode($result);
            die;
        }


       
        if (!$_POST) {
            
            // get permission_id
            $a_up = $s_up->load_all(
                    false, null, null, array('user_id' => $id)
            );
            if ($a_up != null && !empty($a_up[0])) {
                foreach ($a_up as $o_up) {
                    $o_enity_up = $o_up->get_data();
                    $a_permission_id[] = $o_enity_up->getPermission_Id();
                }
            }

            // get group_id
            $a_ug = $s_ug->load_all(
                    false, null, null, array('user_id' => $id)
            );
            if ($a_ug != null && !empty($a_ug[0])) {
                foreach ($a_ug as $o_ug) {
                    $o_enity_ug = $o_ug->get_data();
                    $a_group_id[] = $o_enity_ug->getGroup_Id();
                }
            }
        } else {

            $a_post = $_POST;
            $a_permission_id = empty($a_post['permission_id']) ? null : $a_post['permission_id'];
            $a_group_id = empty($a_post['group_id']) ? null : $a_post['group_id'];
            $en_user->set_array_to_object($a_post);
            $en_user->setedituserid($this->_user->getId());
            $en_user->setDob(Controller_Helper_Format::format_date($en_user->getDob(), 'm/d/Y', "Y-m-d"));
            $result = array();
            $result['error'] = 0;
            
        
            $result = $s_user->valid_edit($en_user, 'en/admin/user/error');
            

            if (empty($result['msg'])) {
                $o_user = $s_user->update($en_user);
                if (!empty($o_user)) {
                    $o_entity_user = $o_user->get_data();
                    $n_user_id = $id;
                    //add User Permission
                    $s_up->delete_by_user_ids($id);
                    if (!empty($a_permission_id) && is_array($a_permission_id)) {

                        foreach ($a_permission_id as $n_permission_id) {
                            $o_entity_up = new Domain_Entities_User_Permission;
                            $o_entity_up->setPermission_Id($n_permission_id);
                            $o_entity_up->setUser_Id($n_user_id);
                            $s_up->insert($o_entity_up);
                        }
                    }
                    //add User Group
                    $s_ug->delete_by_user_ids($id);
                    if (!empty($a_group_id) && is_array($a_group_id)) {

                        foreach ($a_group_id as $n_group_id) {
                            $o_entity_ug = new Domain_Entities_User_Group();
                            $o_entity_ug->setGroup_Id($n_group_id);
                            $o_entity_ug->setUser_Id($n_user_id);
                            $s_ug->insert($o_entity_ug);
                        }
                    }
                }
                if (trim($en_user->getimagename()) != "" && $image_old != trim($en_user->getimagename())) {
                    $url_move = $this->getUrl_base_media() . "/move_file.php";
                    $request = Request::factory($url_move)
                            ->method('POST')
                            ->post('fromfolder', Controller_Helper_Constant::FOLDER_TEMP)
                            ->post('tofolder', Controller_Helper_Constant::FOLDER_AVATAR)
                            ->post('filename', $en_user->getimagename());
                    $response = $request->execute();

                    //delete file
                    $url_delete = $this->getUrl_base_media() . "/delete_file.php";

                    $request = Request::factory($url_delete)
                            ->method('POST')
                            ->post('fromfolder', Controller_Helper_Constant::FOLDER_AVATAR)
                            ->post('filename', $image_old);
                    $response = $request->execute();
                }
                $result['msg'] = Kohana::message('en/admin/user/success', 'edit');
            }
            echo json_encode($result);
            die;
        }
        //get permission controller
        $s_p_controller = new Model_Service_Permission_Controller;
        $a_p_controller = $s_p_controller->load_all();

        //get all group
        $s_group = new Model_Service_Group;
        $a_group = $s_group->load_all();
        $breadcrumbs = array(
            "People" => "",
            "List" => array('onclick' => '_user_list.back_list();', 'href' => 'javascript:;'),
            "Edit" => "",
        );

        $result['msg'] = View::factory("admin/user/edit")
                        ->set('breadcrumbs', $breadcrumbs)
                        ->set('en_user', $en_user)
                        
                        ->set('a_p_controller', $a_p_controller)
                        ->set('a_group', $a_group)
                        ->set('a_permission_id', $a_permission_id)
                        ->set('a_group_id', $a_group_id)->render();
        echo json_encode($result);
        die;
    }

    public function action_detail() {
        header('Content-type: application/json');
        $result = array();
        $id = Arr::get($_REQUEST, 'id');
        $result['error'] = 0;

        $s_user = new Model_Service_User();
        $en_user = $s_user->load($id)->get_data();

       

        if ((int) $en_user->getId() <= 0 ) {
            $result['error'] = 1;
            $result['msg'] = "User is not exsting.";
            echo json_encode($result);
            die;
        }

        $breadcrumbs = array(
            "People" => "",
            "List" => array('onclick' => '_user_list.back_list_detail();', 'href' => 'javascript:;'),
            "Detail" => "",
        );

        $result['msg'] = View::factory("admin/user/detail")
                        ->set('breadcrumbs', $breadcrumbs)
                        ->set('en_user', $en_user)->render();
        echo json_encode($result);
        die;
    }

}

?>
